import React, { Component } from 'react';
import { Space, Modal, Tabs } from "antd";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from "@/components/TheButton";
import { exportSheetTable } from '@/utils/exportTable.js';
import { getShopOrderPage, openCommissionList, getShopOrderList } from '@/request/storeBackManage/fundsManage/billList';
import moment from 'moment'
import _ from 'lodash';

const { TabPane } = Tabs
class Index extends Component {
  state = {
    columns: [
      {
        title: "订单编号",
        dataIndex: "orderCode",
        key: "orderCode",
        width: 200
      },
      {
        title: "所属商家",
        dataIndex: "storeName",
        key: "storeName",
        width: 200
      },
      {
        title: "商家类型",
        dataIndex: "storeChannel",
        key: "storeChannel",
        render: (text) => {
          let label = ''
          switch (text) {
            case 1:
              label = "自营"
              break;
            case 2:
              label = "非自营"
              break;
            default:
              label = "-"
          }
          return label
        }
      },
      {
        title: "分账类型",
        dataIndex: "openCommission",
        key: "openCommission",
        render: (text) => {
          let label = ''
          switch (text) {
            case 0:
              label = "不分账"
              break;
            case 1:
              label = "分账"
              break;
            default:
              label = "-"
          }
          return label
        }
      },
      {
        title: "订单类型",
        dataIndex: "activityTypeCode",
        key: "activityTypeCode",
        render: (text) => {
          let label = ''
          switch (text) {
            case 0:
              label = "普通订单"
              break;
            case 2:
              label = "拼团订单"
              break;
            case 1:
              label = "砍价订单"
              break;
            case 3:
              label = "奖品订单"
              break;
            default:
              label = "字段值错误"
          }
          return label
        }
      },
      {
        title: "订单实付金额(元)",
        dataIndex: "orderPayPrice",
        key: "orderPayPrice",
        width: 150,
        render: (text, record) => {
          return <Space direction={"vertical"}>
            <React.$Price price={text || 0} />
            <span>(含运费：<React.$Price price={record.freight || 0} />)</span>

          </Space>
        }
      },
      {
        title: "订单退款金额(元)",
        dataIndex: "orderSalesReturnPrice",
        key: "orderSalesReturnPrice",
        width: 150,
        render: (text) => {
          return <React.$Price price={text || 0} />
        }
      },
      {
        title: "商家所得(元)",
        dataIndex: "practicalStorePrice",
        key: "practicalStorePrice",
        width: 150,
        render: (text) => {
          return <React.$Price price={text || 0} />
        }
      },
      {
        title: "平台所得(元)",
        dataIndex: "practicalCommission",
        key: "practicalCommission",
        width: 150,
        render: (text, record) => {
          switch (record.commissionStatus) {
            case 0:
              return text = '-'
            case 1:
              return <React.$Price price={text || 0} />
            default:
              return text = '-'
          }
        }
      },
      {
        title: "下单时间",
        dataIndex: "createTime",
        key: "createTime",
        width: 200
      },
      {
        title: "订单状态",
        dataIndex: "orderState",
        key: "orderState",
        render: (text) => {
          let label = ''
          switch (text) {
            case '3':
              label = "待付款"
              break;
            case '4':
              label = "待发货"
              break;
            case '5':
              label = "待收货"
              break;
            case '6':
              label = "待分享"
              break;
            case '9':
              label = "交易成功"
              break;
            case '0':
              label = "交易关闭"
              break;
            default:
              label = "-"
          }
          return label
        }
      },
      {
        title: "结算状态",
        dataIndex: "commissionStatus",
        key: "commissionStatus",
        render: (text) => {
          let label = ''
          switch (text) {
            case 1:
              label = "已结算"
              break;
            case 0:
              label = "未结算"
              break;
          }
          return label
        }
      },
      {
        title: "操作",
        fixed: "right",
        width: 150,
        render: (text, record) => {
          return <TheButton  haspermi={['storeBack:billList:detail']} onClick={() => this.goDetail(record.shopOrderId)}>查看详情</TheButton>
        },
      },
    ],
    tabParams: [
      {
        key: '',
        label: '全部',
      },
      {
        key: '3',
        label: '待付款',
      },
      {
        key: '6',
        label: '待分享',
      },
      {
        key: '4',
        label: '待发货',
      },
      {
        key: '5',
        label: '待收货',
      },
      {
        key: '9',
        label: '交易完成',
      },
      {
        key: '0',
        label: '交易关闭',
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    form_show: true,
    searchOption: [
      {
        field: 'orderCode',
        label: '订单编号',
        placeholder: '请输入订单编号',
        required: false,
        rules: [],
        type: 'Input',
        defaultValue: '',
        maxLength: 30
      },
      {
        field: 'time',
        label: '下单时间',
        placeholder: '请选择',
        required: false,
        rules: [],
        type: 'RangePicker'
      },
      {
        field: 'activityTypeCode',
        label: '订单类型',
        placeholder: '请选择',
        required: false,
        rules: [],
        type: 'Select',
        options: [
          { value: '', label: '全部' },
          { value: 0, label: '普通订单' },
          { value: 1, label: '砍价订单' },
          { value: 2, label: '拼团订单' },
          { value: 3, label: '奖品订单' },
        ],
        defaultValue: ''
      },
      {
        field: 'storeId',
        label: '所属商家',
        placeholder: '请选择',
        required: false,
        rules: [],
        type: 'Select',
        options: [],
        txt: 'storeName',
        value: 'storeId',
        api: openCommissionList,
      },
      {
        field: 'storeChannel',
        label: '商家类型',
        placeholder: '全部',
        required: false,
        rules: [],
        type: 'Select',
        options: [
          { value: '', label: '全部' },
          { value: 1, label: '自营' },
          { value: 2, label: '非自营' },
        ],
        defaultValue: ''
      },
      {
        field: 'commissionStatus',
        label: '结算状态',
        placeholder: '全部',
        required: false,
        rules: [],
        type: 'Select',
        options: [
          { value: '', label: '全部' },
          { value: 0, label: '未结算' },
          { value: 1, label: '已结算' },
        ],
        defaultValue: ''
      },
      {
        field: 'openCommission',
        label: '分账类型',
        placeholder: '全部',
        required: false,
        rules: [],
        type: 'Select',
        options: [
          { value: '', label: '全部' },
          { value: 0, label: '不分账' },
          { value: 1, label: '分账' },
        ],
        defaultValue: ''
      },
    ],
    queryForm: {},
    status: 0,
    tabValue: '',
    exportLoading: false,
  }
  componentDidMount() {
    this.getData()
  }
  // tab切换
  tabChange = (e) => {
    this.setState({ tabValue: e })
    this.pageChange(1, 10)
  }
  /**
   * @desc 获取列表
   * */
  getData = async (value) => {
    const { tabValue, pageData, queryForm } = this.state
    const params = {
      ...pageData,
      ...queryForm,
      orderState: tabValue,
      // openCommission: 1,
      ...value
    }
    if (params.orderState === '') delete params.orderState
    await getShopOrderPage({ ...params }).then(res => {
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount,
        })
      }
    })
  }
  // 详情
  goDetail = (id) => {
    this.props.history.push(`/storeBackManage/fundsManage/billList/detail/${id}`);
  }
  /**
   * @desc 表格组件分页切换
   * @params number|string {pageNo} 页号
   * @params number|string {pageSize} 每页条数
   * */
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => {
      this.getData()
    })
  };
  /**
   * @desc 表格搜索组件重置搜索条件
   * */
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  /**
   * @desc 表格搜索组件搜索
   * */
  onFormSearch(value) {
    if (value && value.hasOwnProperty('time')) {
      value.createTimeStart = moment(value.time[0]).format('yyyy-MM-DD') + ' 00:00:00'
      value.createTimeEnd = moment(value.time[1]).format('yyyy-MM-DD') + ' 23:59:59'
      delete value.time
    }
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
      queryForm: { ...value }
    }, () => {
      this.getData(value)
    })
  }
  /**
   * @desc 表格数据导出
   * */
  toExport = async () => {
    let { queryForm, tabValue } = this.state;
    if (_.isEmpty(queryForm)) {
      Modal.warning({
        title: '请选择筛选条件并查询后再导出对应的订单，暂不支持全量导出。',
      });
      return
    }
    this.setState({ exportLoading: true })
    let params = { ...queryForm, orderState: tabValue }
    if (params.orderState === '') delete params.orderState
    let res = await getShopOrderList({ ...params })
    if (res.code === 0 && res.data) {
      let th_arr = [
        {
          title: '订单对账列表',
          prop: '',
          children: [
            {
              title: "订单编号",
              prop: "orderCode",
            },
            {
              title: "所属商家",
              prop: "storeName",
            },
            {
              title: "商家类型",
              prop: "storeChannel",
            },
            {
              title: "分账类型",
              prop: "openCommission",
            },
            {
              title: "订单类型",
              prop: "activityTypeCode",
            },
            {
              title: "订单实付金额（元）",
              prop: "orderPayPrice",
            },
            {
              title: "订单退款金额(元)",
              prop: "orderSalesReturnPrice",
            },
            {
              title: "商家所得(元)",
              prop: "practicalStorePrice",
            },
            {
              title: "平台所得(元)",
              prop: "practicalCommission",
            },
            {
              title: "下单时间",
              prop: "createTime",
            },
            {
              title: "订单状态",
              prop: "orderState",
            },
            {
              title: "结算状态",
              prop: "commissionStatus",
            },
          ]
        },
      ]
      let tb_arr = []
      res.data.forEach((item) => {
        let { commissionStatus, orderState, activityTypeCode, storeChannel, openCommission } = ''
        // 结算状态
        switch (item.commissionStatus) {
          case 0:
            commissionStatus = "未结算"
            break;
          case 1:
            commissionStatus = "已结算"
            break;
          default:
            commissionStatus = "-"
        }
        // 商家类型
        switch (item.storeChannel) {
          case 1:
            storeChannel = "自营"
            break;
          case 2:
            storeChannel = "非自营"
            break;
          default:
            storeChannel = "-"
        }
        //分账类型
        switch (item.openCommission) {
          case 0:
            openCommission = "不分账"
            break;
          case 1:
            openCommission = "分账"
            break;
          default:
            openCommission = "-"
        }

        //订单状态
        switch (item.orderState) {
          case '3':
            orderState = "待付款"
            break;
          case '4':
            orderState = "待发货"
            break;
          case '5':
            orderState = "待收货"
            break;
          case '6':
            orderState = "待分享"
            break;
          case '9':
            orderState = "交易成功"
            break;
          case '0':
            orderState = "交易关闭"
            break;
          default:
            orderState = "-"
        }
        // 订单类型
        switch (item.activityTypeCode) {
          case 0:
            activityTypeCode = "普通订单"
            break;
          case 1:
            activityTypeCode = "砍价订单"
            break;
          case 2:
            activityTypeCode = "拼团订单"
            break;
          case 3:
            activityTypeCode = "奖品订单"
            break;
          default:
            activityTypeCode = "-"
        }
        tb_arr.push({
          ...item,
          storeChannel,
          commissionStatus,
          orderState,
          activityTypeCode,
          openCommission,
          orderPayPrice: '￥' + (item.orderPayPrice / 100).toFixed(2) || '￥0.00',
          orderSalesReturnPrice: '￥' + (item.orderSalesReturnPrice / 100).toFixed(2) || '￥0.00',
          practicalStorePrice: '￥' + (item.practicalStorePrice / 100).toFixed(2) || '￥0.00',
          practicalCommission: '￥' + (item.practicalCommission / 100).toFixed(2) || '￥0.00'
        })

      })
      exportSheetTable({ fileName: '订单对账列表', tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false })
    }
    this.setState({ exportLoading: false })
  }
  statusChange = (value) => {
    console.log(value)
  }
  render() {
    let { columns, dataSource, pageData: { pageNo, pageSize }, total, searchOption, form_show, status, tabParams, tabValue } = this.state;
    return (
      <div className={"p-layout-box commodity-content"}>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
          <TheButton haspermi={['storeBack:billList:export']} size="middle" onClick={() => this.toExport()} type="default">导出</TheButton>
        </TheQueryForm>
        <Tabs onChange={this.tabChange} >
          {tabParams.map((item, index) => {
            return <TabPane key={item.key} tab={item.label}>
              <TheTable scroll={{ x: '960', y: '63vh' }} columns={columns} dataSource={dataSource} rowKey={'orderCode'}></TheTable>
              <ThePagination
                pageNo={pageNo}
                pageSize={pageSize}
                total={total}
                pageChange={this.pageChange}
              ></ThePagination>
            </TabPane>
          })}
        </Tabs>

      </div >
    );
  }
}

export default Index;
